c
is initialized to a reference
to a String object containing no characters.
This is most certainly a different value than null.
A String object that contains no characters is still an object. Sometimes such an object is called an empty string. It is similar to having a blank sheet of paper, versus having no paper at all. Overlooking this distinction is one of the classic confusions of computer programming. It will happen to you. It still happens to me. To prepare for future confusion, study the program, step-by-step:
class NullDemo1 { public static void main (String[] arg) { String a = "Random Jottings"; // 1. an object is created; // variable a refers to it String b = null; // 2. variable b refers to no object. String c = ""; // 3. an object is created // (containing no characters); // variable c refers to it if ( a != null ) // 4. ( a != null ) is true, so System.out.println( a ); // 5. the println( a ) executes. if ( b != null ) // 6. ( b != null ) is false, so System.out.println( b ); // 7. the println( b ) is skipped. if ( c != null ) // 8. ( c != null ) is true, so System.out.println( c ); // 9. the println( c ) executes. // (but it has no characters to print.) } }
The System.out.println()
method
expects a reference to a String object as a parameter
.
The example program tests that each variable contains a String reference
before calling println()
with it.
(Actually, println()
will
not crash if it gets a null
.
But some methods will.
Usually you should insure that methods get the data they expect).